/*
作者：江怀玉
日期：2014-05-09
功能：自动完成选择信息
解决：
1、取数据问题
2、条件
3、数据显示
4、选值
-------------------------------------
依赖:
jquery,
/scripts/jquery.data.js :fnGetData
---------------------------------------------------------*/
(function ($) {
    $.fn.Commbox = function (options) {
        //debugger
        var _opt = !options ? { "entity": "V_User"} : options;
        var v = $(this).attr("valuemember");   //值字段
        var d = $(this).attr("displaymember"); //显示在控件中字段
        var f = $(this).attr("filter");        //过滤字段
        var t = $(this).attr("top");           //显示几行
        var lw = $(this).attr("listwidth");    //弹出的列表宽度
        var lh = $(this).attr("listheight");    //弹出的列表高度
        var l = $(this).attr("listMember");    //显示的列表字段
        var _l = l == undefined || l == "" ? [{ F: "caption", W: "250px"}] : eval(l); //显示的列表字段
        var arrayf = new Array();              //定义要过滤的字段组
        arrayf = f.split(',');
        var $this = this;
        var _data = null;
        var _smode = $(this).attr("SelectMode"); //当前模式 

        var _event = $(this).attr("event");
        var _isloaddata = $(this).attr("isloaddata");
        _isloaddata = (_isloaddata == undefined || _isloaddata == "") ? 'true' : _isloaddata;
        lw = (lw == undefined || lw == "") ? '' : lw;
        lh = (lh == undefined || lh == "") ? '' : lh;

        var defaults = {
            id: $(this).attr("id"),
            entity: $(this).attr("entity"), //对应实体 
            sort: $(this).attr("sort"),    //排序
            condition: $(this).attr("condition"), //条件
            filter: f == undefined || f == "" ? "caption" : f,        //过滤字段
            valuemember: v == undefined || v == "" ? "id" : v,        //值字段
            displaymember: d == undefined || d == "" ? "caption" : d, //显示字段
            top: t == undefined || t == "" ? "25" : t,                //
            list: _l,                                                 //显示列表
            listwidth: lw,                                              //显示弹出的列表宽度
            listheight: lh,
            event: $(this).attr("event"),                               //事件方法
            isloaddata: _isloaddata       //默认加载数据，否则鼠标点击加载数据
        };

        $(this).wrap("<div id=\"Dept_" + defaults.id + "\" class=\"deptctrl\" style=\"width:" + (this.width() + 20) + "px\"></div>");
        $(this).width(this.width() - 18);
        $(this).after('<input type="button" class="button" id="btn_' + defaults.id + '"/>');
        //GetData($(this).attr("entity"), $(this).attr("condition"), $(this).attr("sort"));

        function GetData(entity, condition, sort) {
            //debugger
            return fnGetData(entity, condition, sort, "YES");
        }

        $("#btn_" + defaults.id).click(function () {
            //debugger;
            if ($('#' + defaults.id).attr('readonly') == 'readonly') {
                return false;
            }
            if ($('#' + defaults.id).attr('disabled') == 'disabled') {
                return false;
            }

            //加载数据
            if (defaults.isloaddata.toLowerCase() == 'false') SetDataTable();

            if (_smode == "m") {
                var _v = $("#" + defaults.id).attr("SValue");
                if (_v != "" && _data != null) {
                    $("#" + defaults.id + "div_gridshow").find("input[type='checkbox']").each(function () {
                        $(this).attr("checked", isExist(_v, $(this).val()));
                    });
                }
                $("#" + defaults.id + "mcomid").show();
            }

            //重新定位高度，左边没有加入
            var _top = $("#" + defaults.id).offset().top + 25;
            $("#" + defaults.id + "div_gridshow").css({ top: _top });

            $("#" + defaults.id + "div_gridshow").show();
        });


        //是否存在
        function isExist(_str, _cstr) {
            var flg = false;
            if (_str == "" || _cstr == "") return flg;
            var ary = (_str != "") ? _str.split(",") : new Array();
            var len = ary.length;
            if (len == 0) return flg;
            for (var i = 0; i < len; i++) {
                if (ary[i] == _cstr) {
                    flg = true;
                    break;
                }
            }
            return flg;
        }

        //搜索条件
        function getCondition(key, _fields) {
            var _condition = "";

            if (!key) return _condition;
            for (i = 0; i < _fields.length; i++) {
                if (i == 0) {
                    _condition = _condition + " (" + _fields[i] + " like '%" + key + "%')  ";
                }
                else {
                    _condition = _condition + " or (" + _fields[i] + " like '%" + key + "%')  "
                }
            }

            return _condition == "" ? "" : "(" + _condition + ")";
        }

        var o_value = "";
        var timer = 0; //记时器
        $(this).bind("keyup", function (e) {
            if (e.which != 13 && e.which != 40 && e.which != 38) {
                if (o_value == $(this).val()) {
                    return;
                }
                o_value = $(this).val();

                //-------用来确保只执行一次有效的数据拉取
                clearTimeout(timer);
                timer = setTimeout(SetDataTable, 1500);
            }
        }).focus(function () {
            $(this).select();
        });

        if (defaults.isloaddata.toLowerCase() == 'true') SetDataTable();

        function SetDataTable() {
            //debugger
            var key = o_value;
            var condition = getCondition(key, arrayf);

            defaults.condition = "(" +  $($this).attr("condition") + ")";
            //增加条件
            var cs_condition = ((defaults.condition == "" || defaults.condition == undefined) ? "" : defaults.condition);

            condition = condition + ((cs_condition != "" && condition != "") ? " and " : "") + cs_condition;

            _data = GetData(defaults.entity, condition, defaults.sort);
            if (_data == undefined) {
                LoadData(null);
                return;
            }
            if (_data == null) {
                LoadData(null);
                return;
            }
            LoadData(_data.rows);
            //$("#" + defaults.id + "div_gridshow").show();
            if (_smode == "m") $("#" + defaults.id + "mcomid").hide();
        }


        // 加载数据
        function LoadData(rows) {
            if (rows == null) { rows = []; }
            var html = "";
            var _slist = defaults.list;
            var _valname = $("#" + defaults.id).attr("valuemember");
            var _colwidth = 0, _rowheight = 240;
            for (var i = 0; i < rows.length; i++) {
                var list = rows[i];
                html += "<tr index='" + i + "'>";
                for (var _index = 0; _index < _slist.length; _index++) {
                    if (i == 0) _colwidth += parseInt(_slist[_index].W);
                    if (_smode == "m" && _valname == _slist[_index].F)
                        html += '<td style="width: ' + _slist[_index].W + ';"><input field=' + i + ' type="checkbox" value="' + rows[i][_slist[_index].F] + '"></td>';
                    else
                        html += '<td style="width: ' + _slist[_index].W + ';">' + rows[i][_slist[_index].F] + '</td>';
                }
                html += "</tr>";
            }

            if (defaults.listwidth != "") _colwidth = defaults.listwidth;
            if (defaults.listheight != "") _rowheight = defaults.listheight;
            _colwidth = (_colwidth == 0) ? 200 : _colwidth;
            //alert(_colwidth);

            //点击事件回调
            autocomplete(defaults.id, _colwidth, _rowheight, html, function (r) {
                $("#" + defaults.id).attr("SValue", r[defaults.valuemember]);
                $("#" + defaults.id).val(r[defaults.displaymember]);
                if (_event != "") {
                    eval(_event);
                }
            });
        }
        //方向键上,方向键下,回车键
        function autocompletekeydown(Objkey, callBack) {
            $("#" + Objkey).keydown(function (e) {
                switch (e.keyCode) {
                    case 38: // 方向键上
                        if (IndetableRow_autocomplete > 0) {
                            IndetableRow_autocomplete--
                            $("#" + defaults.id + "div_gridshow").find('tbody tr').removeClass('selected');
                            $("#" + defaults.id + "div_gridshow").find('tbody tr').each(function (r) {
                                if (r == IndetableRow_autocomplete) {
                                    scrollTopheight -= $(this).height();
                                    $("#" + defaults.id + "div_gridshow").scrollTop(scrollTopheight);
                                    $(this).addClass('selected');
                                }
                            });
                        }
                        break;
                    case 40: // 方向键下
                        var tindex = $("#" + defaults.id + "div_gridshow").find('tbody tr').length - 1;
                        if (IndetableRow_autocomplete < tindex) {
                            IndetableRow_autocomplete++;
                            $("#" + defaults.id + "div_gridshow").find('tbody tr').removeClass('selected');
                            $("#" + defaults.id + "div_gridshow").find('tbody tr').each(function (r) {
                                if (r == IndetableRow_autocomplete) {
                                    scrollTopheight += $(this).height();
                                    $("#" + defaults.id + "div_gridshow").scrollTop(scrollTopheight);
                                    $(this).addClass('selected');
                                }
                            });
                        }
                        break;
                    case 13:  //回车键

                        if ($('#' + Objkey).attr('readonly') == 'readonly') {
                            return false;
                        }
                        if ($('#' + Objkey).attr('disabled') == 'disabled') {
                            return false;
                        }
                        if (_smode == "s") {
                            var _index = IndetableRow_autocomplete;
                            var _e = _data.rows[_index];
                            callBack(_e);
                            $("#" + defaults.id + "div_gridshow").hide();

                        }
                        break;
                    default:
                        break;
                }
            })
        }

        //上，下键盘回调
        autocompletekeydown(defaults.id, function (obj) {
            //var array = new Array();
            //array = r.split('≌');
            //设置值
            if (_smode == "s") {
                $("#" + defaults.id).val(obj[defaults.displaymember]);
                $("#" + defaults.id).attr("SValue", obj[defaults.valuemember]);
            }
        });




        //自动补全表格
        var IndetableRow_autocomplete = 0;
        var scrollTopheight = 0;
        function autocomplete(Objkey, width, height, data, callBack) {
            if ($('#' + Objkey).attr('readonly') == 'readonly') {
                return false;
            }
            if ($('#' + Objkey).attr('disabled') == 'disabled') {
                return false;
            }
            IndetableRow_autocomplete = 0;
            scrollTopheight = 0;
            var X = $("#" + Objkey).offset().top;
            var Y = $("#" + Objkey).offset().left;
            $("#" + defaults.id + "div_gridshow").html("");

            //debugger;
            //function GetPosition(obj) { var left = 0; var top = 0; while (obj != document.body) { left = obj.offsetLeft; top = obj.offsetTop; obj = obj.offsetParent; } alert("Left Is : " + left + "\r\n" + "Top   Is : " + top); }
            //GetPosition($("#" + Objkey)[0]);
            if ($("#" + defaults.id + "div_gridshow").attr("id") == undefined) {
                $('body').append('<div id="' + defaults.id + 'div_gridshow" style="overflow-y: auto;z-index: 9999;border: 1px solid #A8A8A8;width:' + width + 'px;height:' + height + 'px;position: absolute; background-color: #fff; display: none;"></div>');
            }
            //else 
            {
                $("#" + defaults.id + "div_gridshow").height(height);
                $("#" + defaults.id + "div_gridshow").width(width);
            }

            var sbhtml = _smode == "m" ? ('<div id="' + defaults.id + '_div_grid" class="ComBoxDiv" style="overflow-y:auto;width:' + width + 'px;height:' + (height - 25) + 'px;">') : "";
            sbhtml += '<table class="tableobj">';
            if (data != "") {
                sbhtml += '<tbody>' + data + '</tbody>';
            } else {
                sbhtml += '<tbody><tr><td style="color:red;text-align:center;width:' + width + ';">没有找到您要的相关数据！</td></tr></tbody>';
            }
            sbhtml += '</table>';
            if (_smode == "m") {
                sbhtml += '</div><div style="text-align:center;border-top:1px solid #a8a8a8; margin:1px 0px 0px; padding-top:3px; width:' + width + 'px;"><button id="btn_' + defaults.id + '_ok" class="btn btn-danger">确定</button> <button id="btn_' + defaults.id + '_cancel" class="btn btn-danger">取消</button></div>';
            }
            $("#" + defaults.id + "div_gridshow").html(sbhtml);

            $("#" + defaults.id + "div_gridshow").css("left", Y).css("top", X + 25);

            if (_smode == "m") {
                $("#" + defaults.id + "_div_grid").height(height - 40);
                $("#" + defaults.id + "_div_grid").width(width);

                //var rel = $("<input type='button'  value='确定' />").bind("click", function () {
                $('#btn_' + defaults.id + '_ok').bind("click", function () {
                    //debugger;
                    var _thesel = '', _thetxt = '';
                    $("#" + defaults.id + "div_gridshow").find("input[type='checkbox']:checked").each(function () {
                        _thesel += ((_thesel == '' ? '' : ',') + $(this).val());
                        var _index = $(this).attr("field");
                        _thetxt += ((_thetxt == '' ? '' : ',') + _data.rows[_index][d]);
                    });

                    if (_thesel == "") { alert("请选择信息"); return; }


                    $("#" + defaults.id).attr("SValue", _thesel);
                    $("#" + defaults.id).val(_thetxt);

                    $("#" + defaults.id + "div_gridshow").hide();
                    $("#" + defaults.id + "mcomid").hide();
                });
                //var cls = $("<input type='button'  value='取消'/>").bind("click", function () {
                $('#btn_' + defaults.id + "_cancel").bind("click", function () {
                    $("#" + defaults.id + "div_gridshow").hide();
                    $("#" + defaults.id + "mcomid").hide();
                });
                //var _top = parseInt(height) + X;
                //var _left = parseInt(width) / 3 + Y;
                //var _btnl = $("<div id='" + defaults.id + "mcomid' style='position:absolute;z-index: 1000;'/>").append(rel).append(cls).css("left", _left).css("top", _top).hide();
                //$("#" + defaults.id + "div_gridshow").after(_btnl);
            }


            if (data != "") {
                $("#" + defaults.id + "div_gridshow").find('tbody tr').each(function (r) {
                    if (r == 0) {
                        $(this).addClass('selected');
                    }
                });
            }

            $("#" + defaults.id + "div_gridshow").find('tbody tr').click(function () {
                if (_smode == "s") {
                    var _index = parseInt($(this).attr("index"));
                    var _e = _data.rows[_index];
                    callBack(_e);

                    if ($('#' + Objkey).attr('readonly') == 'readonly') {
                        return false;
                    }
                    if ($('#' + Objkey).attr('disabled') == 'disabled') {
                        return false;
                    }
                    $("#" + defaults.id + "div_gridshow").show();
                }
                else {
                    //点击行撤销或选择当前信息
                    $(this).find("input[type='checkbox']").attr("checked", !$(this).find("input[type='checkbox']").attr("checked"));
                }
            });
            $("#" + defaults.id + "div_gridshow").find('tbody tr').hover(function () {
                $(this).addClass("selected");
            }, function () {
                $(this).removeClass("selected");
            });

            //当查询的值只有一条满足条件，就直接选择当前记录信息，即输入数据满足条件直接设置
            if (_data != null && _data.rows != null) {
                var rownumber = _data.rows.length;
                if (rownumber == 1) { setTimeout(function () { EnterSet(_data.rows); }, 1000); }
            }
        }
        //任意键关闭
        $(document).bind("click", function (e) {
            var e = e ? e : window.event;
            var tar = e.srcElement || e.target;
            if ($(tar).attr("id") == "btn_" + defaults.id) { return false; } //but按钮事件导致该事件执行，层被隐藏
            if ($(tar).attr("field") != "" && $(tar).attr("field") != undefined) { return false; } //多项选择选中时，不能隐藏。
            //if (tar.id.indexOf('div_gridshow')<=0) {
            if ($(tar).attr("id") == defaults.id + 'div_gridshow' || $(tar).attr("id") == defaults.id) {
                if ($('#' + defaults.id).attr('readonly') == 'readonly') {
                    return false;
                }
                if ($('#' + defaults.id).attr('disabled') == 'disabled') {
                    return false;
                }
                //debugger
                if (defaults.isloaddata.toLowerCase() == 'false' && $(tar).attr("id") == defaults.id) SetDataTable();

                //重新定位高度，左边没有加入
                var _top = $("#" + defaults.id).offset().top + 25;
                $("#" + defaults.id + "div_gridshow").css({ top: _top });

                $("#" + defaults.id + "div_gridshow").show();
                if (_smode == "m") $("#" + defaults.id + "mcomid").show();
            } else {
                $("#" + defaults.id + "div_gridshow").hide();
                if (_smode == "m") $("#" + defaults.id + "mcomid").hide();
            }

            //当前插件的自动选中数据设置
            if (_data != null && _data.rows != null && ($(tar).attr("id") == defaults.id + 'div_gridshow' || $(tar).attr("id") == defaults.id)) {
                EnterSet(_data.rows);
            }
            //}
        });


        //设置选中数据判断
        var EnterSet = function (rows) {
            if (!rows || rows.length == 0) return false;

            if ($('#' + defaults.id).attr('readonly') == 'readonly' || $('#' + defaults.id).attr('disabled') == 'disabled') {
                return false;
            }

            var flag = false;
            var val = dis = '';
            if (rows.length == 1) {
                flag = true;
                val = rows[0][defaults.valuemember];
                dis = rows[0][defaults.displaymember];
            }
            else {
                var keyword = $("#" + defaults.id).val();
                for (var i = 0; i < rows.length; i++) {
                    if (keyword == rows[i][defaults.displaymember]) {
                        flag = true;
                        val = rows[i][defaults.valuemember];
                        dis = rows[i][defaults.displaymember];
                        break;
                    }
                }
            }

            if (!flag) return false;

            $("#" + defaults.id).attr("SValue", val);
            $("#" + defaults.id).attr("SText", dis);
            $("#" + defaults.id).val(dis);
            $("#" + defaults.id + "div_gridshow").hide();

            if (defaults.fn != "") {
                eval(defaults.event);
            }
        };

    }

})(jQuery);



//初始化控件
$(document).ready(function () {
    var controls = $(this).find('input');
    controls.each(function () {
        if ($(this).attr("ctrlType") == "Commbox") {
            $(this).Commbox();
        }
    });
});
/*
-------------------------------------
样例:
<input type="text" SValue="" SText="" id="Dept" value="" ctrlType="AutoComplete" SelectMode="s" entity="V_Dept" filter="DeptPath,name" valuemember="DeptPath" displaymember="name" listMember="[{F:'name',W:'150px'},{F:'DeptPath',W:'120px'}]"/>
<input type="text" SValue="" SText="" id="UName" value="" ctrlType="AutoComplete" SelectMode="s" entity="DatUser" filter="LoginName,UName" valuemember="LoginName" displaymember="UName" listMember="[{F:'LoginName',W:'150px'},{F:'UName',W:'120px'}]"/>
-------------------------------------
另：
//(function ($) {
//    $.fn.delayKeyup = function (callback, ms) {
//        var timer = 0;
//        $(this).keyup(function () {
//            clearTimeout(timer);
//            timer = setTimeout(callback, ms);
//        });
//        return $(this);
//    };
//})(jQuery)；
<link href="/scripts/yui_2.9.0/build/container/assets/skins/sam/container.css" rel="stylesheet" type="text/css" />
<link href="/scripts/yui_2.9.0/build/button/assets/skins/sam/button.css" rel="stylesheet" type="text/css" />
<link href="/scripts/yui_2.9.0/build/layout/assets/skins/sam/layout.css" rel="stylesheet" type="text/css" />
<link href="/Scripts/yui_2.9.0/build/datatable/assets/skins/sam/datatable.css" rel="stylesheet" type="text/css" />
<link href="/Scripts/yui_2.9.0/build/resize/assets/skins/sam/resize.css" rel="stylesheet" type="text/css" />
*/


